package com.open.capacity.notice.provider;

import javax.annotation.Resource;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.plugin.core.PluginRegistry;
import org.springframework.plugin.core.config.EnablePluginRegistries;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.open.capacity.notice.provider.core.http.ThOkHttp3Template;
import com.open.capacity.notice.provider.sms.SmsProperties;
import com.open.capacity.notice.provider.sms.SmsTemplate;
import com.open.capacity.notice.provider.wechat.WechatProperties;
import com.open.capacity.notice.provider.wechat.WechatTemplate;
import com.open.capacity.notice.provider.wechat.chain.WechatMessageChain;

import okhttp3.OkHttpClient;

@Configuration
@ComponentScan({ "com.open.capacity.notice" })
@EnablePluginRegistries(NoticeTemplate.class)
@EnableConfigurationProperties({ SmsProperties.class, WechatProperties.class })
public class NoticeAutoConfig {

	@Resource
	private PluginRegistry<NoticeTemplate, String> noticeTemplateRegistry;

	@Bean
	public ThOkHttp3Template thOkHttp3Template(ObjectProvider<OkHttpClient> okhttp3ClientProvider,
			ObjectProvider<ObjectMapper> objectMapperProvider ) {

		OkHttpClient okhttp3Client = okhttp3ClientProvider.getIfAvailable(() -> new OkHttpClient.Builder().build());
		@SuppressWarnings("deprecation")
		ObjectMapper objectMapper = objectMapperProvider.getIfAvailable(() -> {
			ObjectMapper defaultObjectMapper = new ObjectMapper();
			defaultObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
			defaultObjectMapper.enable(MapperFeature.USE_GETTERS_AS_SETTERS);
			defaultObjectMapper.enable(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS);
			defaultObjectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
			defaultObjectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
			return defaultObjectMapper;
		});
		return new ThOkHttp3Template(okhttp3Client, objectMapper);
	}

	@Bean
	public SmsTemplate smsTemplate(ThOkHttp3Template thOkHttp3Template, SmsProperties SmsProperties) {
		return new SmsTemplate(thOkHttp3Template, SmsProperties);
	}

	@Bean
	public WechatTemplate wechatTemplate(ThOkHttp3Template wechatOkHttp3Template, WechatProperties wechatProperties,WechatMessageChain wechatMessageChain) {
		return new WechatTemplate(wechatOkHttp3Template, wechatProperties,wechatMessageChain);
	}

	@Bean
	public NoticeTemplateFacotoy noticeTemplate() {
		return new NoticeTemplateFacotoy(noticeTemplateRegistry);
	}

}
